package main.java.com.lee.procon;

import java.util.LinkedList;
import java.util.List;

/**
 * @Description TODO
 * @Author winston
 * @DateTime 2021/12/19
 */
public class DataBuffer<T> {
    private List<T> cache = new LinkedList<>();
    private int limit = 10;
    private int size = 0;

    private final Object LOCK_OBJECT = new Object();
    private final Object NOT_FULL = new Object();
    private final Object NOT_EMPTY = new Object();

    public synchronized boolean put(T t) {
        if (size < limit) {
            cache.add(t);
            size++;
            if (size != cache.size()) {
                throw new RuntimeException("系统异常");
            }
        }

        return true;
    }



    public synchronized T fetch() {
        if (cache.size() > 0 && cache.size() == size) {
            cache.remove(0);
            size--;
            if (cache.size() != size) {
                throw new RuntimeException("系统异常");
            }
            if (cache.size() == 0) {
                return null;
            }
        }
        return null;
    }



    public void put2(T t) throws InterruptedException {

        while (size >= limit) {
            synchronized (NOT_FULL) {
                System.out.println("队列已满");
                NOT_FULL.wait();
            }
        }
        synchronized (LOCK_OBJECT) {
            cache.add(t);
            size++;
        }

        synchronized (NOT_EMPTY) {
            NOT_EMPTY.notify();
        }
    }

    public T fetch2() throws InterruptedException {
        while (size <= 0) {
            synchronized (NOT_EMPTY) {
                System.out.println("队列已空");
                NOT_EMPTY.wait();
            }
        }
        T ele=null;
        synchronized (LOCK_OBJECT) {
            ele = cache.remove(0);
        }

        synchronized (NOT_FULL) {
            NOT_FULL.notify();
        }
        return ele;
    }
}
